import axios from 'axios';
import {
  AuthProvider,  findOrCreateUser,  getGoogleOAuthTokens , getUserByUsername
} from '../../../services/uctoo/uctoo_user';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
import { authorizeAndEnd } from '../../../helpers/authorizeAndEnd';
import { defaultRouteHandler } from '../../../../interfaces';
import log from '../../../helpers/logger';
import {  UctooUser } from '../../../services/uctoo/uctoo_user.types';
import db from "../../../lib/db";
import Logger from '../../../helpers/logger';
import Cookies from 'js-cookie'
import * as qs from 'qs';
import * as bcrypt from 'bcryptjs';

const { GOOGLE_APP_ID, FRONTEND_URL, API_URL } = process.env;

const env = process.env.NODE_ENV;
const isDev = env === 'development';

const handleLogin: defaultRouteHandler = async (req, res) => {
  try {
    const body = await req.json();
    const { username, password, verifyCode } = body;
    
    const user = await getUserByUsername(username);
    if (!user) return res.status(404).end();

    const passwordMatch = await bcrypt.compare(password, user.password);
   
    await bcrypt.hash(password, 10).then((hash) => {
      //console.log(hash);
    });
    if (!passwordMatch) return res.status(400).json({ errcode: "42007", errmsg: "login failed,email/password not match" });

    return authorizeAndEnd(user, req, res, AuthProvider.Local, true);
  } catch (e) {
    log.error(e);
    res
      .status(500)
      .json({ err: e.message, desc: e.response.data.error_description });
  }
};

export default handleLogin;
